import {Component, ViewChild} from '@angular/core';
import {Content, IonicPage, NavController, NavParams, Refresher} from 'ionic-angular';
import {HttpClient} from "@angular/common/http";
import {PageSplit} from "../../utils/page/page";
import {AppUrl, TIME_OUT} from "../../../app/app.general";
import {AppConfig} from "../../../app/appConfig";
import {LoginService} from "../../login/login.service";
import {CommonService} from "../../../app/common.service";

/**
 * Generated class for the AccountManagePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-account-manage',
  templateUrl: 'account-manage.html',
})
export class AccountManagePage {
  @ViewChild(Content) content: Content;
  @ViewChild(Refresher) refresher: Refresher;
  private page:PageSplit = {
    pageSize: 10,
    pageNo: 0,
    isLastPage: false
  };
  private dataList:any = [];
  constructor(public navCtrl: NavController, public navParams: NavParams,private http:HttpClient,private appConfig:AppConfig,private loginService:LoginService,private commonService:CommonService) {
  }

  showAddPage(){
    this.navCtrl.push('AccountAddPage',{type:'admin'});
  }

  getByPage(refresher?: any) {
    this.page.pageNo++;
    this.http.post(AppUrl.user.getAll,this.page).subscribe(res => {
      let temp:any = res;
      if (refresher) {
        this.refresher.complete();
        this.dataList = [];
      }
      if (temp.code === 200){
        this.dataList = this.dataList.concat(temp.data.list);
        this.page.isLastPage = temp.data.isLastPage;
      }
      else {
        this.appConfig.presentToast(temp.msg);
      }
    });
  }

  doInfinite(infiniteScroll):Promise<any> {
    return new Promise(resolve => {
      let that = this;
      setTimeout(function () {
        if (!that.page.isLastPage){
          that.getByPage();
          resolve();
        }
        else {
          resolve();
        }
      },1000);
    });
  }

  ionViewWillEnter(){
    this.refresher._top = '50px';
    this.refresher.state = 'refreshing';
    this.refresher._beginRefresh();
    // this.doRefresh();
  }

  editUser(item){
    this.navCtrl.push('AccountAddPage',{data:item,type:'admin'});
  }

  doRefresh() {
    this.page = {
      isLastPage: false,
      pageSize: 10,
      pageNo: 0
    };
    this.getByPage(this.refresher);
  }

  deleteUser(userid,i){
    this.loginService.delete(userid).timeout(TIME_OUT).subscribe(res=>{
      if (res.code === 200){
        this.appConfig.presentToast('删除成功',1000);
        this.dataList.splice(i,1);
      }
      else {
        this.appConfig.presentToast(res.msg);
      }
    },reject=>{
      this.commonService.httpError(reject);
    });
  }

}
